package com.sk.leetcode.arithmetic;

/**
 * 给定一个链表，旋转链表，将链表每个节点向右移动 k 个位置，其中 k 是非负数。
 * 输入: 1->2->3->4->5->NULL, k = 2
 * 输出: 4->5->1->2->3->NULL
 * 解释:
 * 向右旋转 1 步: 5->1->2->3->4->NULL
 * 向右旋转 2 步: 4->5->1->2->3->NULL
 * <p>
 * 输入: 0->1->2->NULL, k = 4
 * 输出: 2->0->1->NULL
 * 解释:
 * 向右旋转 1 步: 2->0->1->NULL
 * 向右旋转 2 步: 1->2->0->NULL
 * 向右旋转 3 步: 0->1->2->NULL
 * 向右旋转 4 步: 2->0->1->NULL
 */
public class Test61 {
    public static void main(String[] args) {
        int[] ints = {1, 2, 3, 4, 5};
        ListNode head = new ListNode(ints[0]);
        ListNode next = head;
        for (int i = 1; i < ints.length; i++) {
            next.next = new ListNode(ints[i]);
            next = next.next;
        }
        ListNode res = rotateRight(head, 5);
        while (res != null) {
            System.out.println(res.val);
            res = res.next;
        }
    }

    public static ListNode rotateRight(ListNode head, int k) {
        if(head == null || head.next == null || k == 0) {
            return head;
        }
        ListNode res = head;
        ListNode next = head;
        int length = 0;
        while (next != null) {
            length++;
            next = next.next;
        }
        int x = k % length;
        if(x == 0) {
            return head;
        }
        int n = 0;
        ListNode lin = null;
        ListNode pre = null;
        while (true) {
            if(n == (length - x)) {
                if(pre.next != null) {
                    pre.next = null;
                }
                if(lin.next != null) {
                    lin = lin.next;
                } else {
                    lin.next = head;
                    return res;
                }
            } else {
                n++;
                pre = res;
                lin = res = res.next;
            }
        }

    }
}
